package com.wmlive.hhvideo.heihei.db.manager;

import android.content.Context;
import android.text.TextUtils;

import com.wmlive.hhvideo.heihei.db.datatable.IMMessageUserTable;
import com.wmlive.hhvideo.heihei.db.datatable.IMMessageUserTableDao;

import org.greenrobot.greendao.query.QueryBuilder;

import java.util.ArrayList;
import java.util.List;

/**
 * IM 消息中指定用户的数据库管理
 * Created by kangzhen on 2017/7/7.
 */

public class IMMessageUserDBManager {

    private Context mContext;
    private static IMMessageUserDBManager mInstance;

    private IMMessageUserTableDao imMessageTableDao;

    private IMMessageUserDBManager(Context context)
    {

        mContext = context;
    }

    public static IMMessageUserDBManager getInstance(Context context) {
        if (mInstance == null || mInstance.imMessageTableDao==null) {
            synchronized (IMMessageUserDBManager.class) {
                if(mInstance==null || mInstance.imMessageTableDao==null){
                    mInstance = new IMMessageUserDBManager(context);
                    mInstance.imMessageTableDao = new GreenDaoUserDBManager(context).getIMMessageUserTableDao();
                }
            }
        }
        return mInstance;
    }

    /**
     *切换用户数据库
     */
    public static void switchUserDBManager(Context context){
        if(mInstance!=null && mInstance.imMessageTableDao!=null){
            mInstance.imMessageTableDao = null;
        }
        mInstance = null;
        mInstance = new IMMessageUserDBManager(context);
        mInstance.imMessageTableDao = new GreenDaoUserDBManager(context).getIMMessageUserTableDao();
    }

    //==============================add ========================

    /**
     * 统计数据表中的数量
     * @return
     */
    public long getIMMessageAllCount(){
        QueryBuilder<IMMessageUserTable> qb = imMessageTableDao.queryBuilder();
        return qb.buildCount().count();
    }
    /**
     * 获取未消息数量
     * @return
     */
    public synchronized long getImUserEntryUnReadCount(){
        QueryBuilder qb =imMessageTableDao.queryBuilder();
        qb.where(IMMessageUserTableDao.Properties.IsRead.eq(0));
        return qb.buildCount().count();
    }


    /**
     * 添加
     * @param entry
     * @return
     */
    public long insertIMUserData(IMMessageUserTable entry){
        if(entry==null){
            return -1;
        }
        return imMessageTableDao.insert(entry);
    }

    /**
     * 保存
     * @param entry
     * @return
     */
    public long saveIMUserData(IMMessageUserTable entry){
        if(entry==null){
            return -1;
        }
        return imMessageTableDao.insertOrReplace(entry);
    }

    /**
     * 批量保存数据
     * @param datas
     * @return
     */
    public long saveIMUserDateByIte(Iterable<IMMessageUserTable> datas){
        if(datas==null){
            return -1;
        }
        imMessageTableDao.insertOrReplaceInTx(datas);
        return 1;
    }
    //==============================update ========================

    /**
     * 更新单个实例
     * @param entry
     */
    public void updateIMUserDataByEntry(IMMessageUserTable entry){
        if(entry==null){
            return ;
        }
        imMessageTableDao.update(entry);
    }
    //==============================select ========================
    /**
     * 获取单个实例通过id
     * @param msgId
     */
    public IMMessageUserTable getIMUserEntryByMsgId(String msgId){
        IMMessageUserTable entry =null;
        try {
            if (TextUtils.isEmpty(msgId)) {
                return null;
            }
            QueryBuilder qb = imMessageTableDao.queryBuilder();
            qb.where(IMMessageUserTableDao.Properties.Msg_id.eq(msgId));
            qb.limit(1);
            List<IMMessageUserTable> entrys = qb.list();
            if (entrys != null && entrys.size() > 0) {
                entry= entrys.get(0);
            }
        }catch (Exception e){

        }
        return entry;
    }
    /**
     * 获取单个实例通过id
     * @param listId
     */
    public IMMessageUserTable getIMUserEntryByListId(Long listId){
        IMMessageUserTable entry =null;
        try {
            if (listId==null) {
                return null;
            }
            QueryBuilder qb = imMessageTableDao.queryBuilder();
            qb.where(IMMessageUserTableDao.Properties.Listid.eq(listId));
            qb.limit(1);
            List<IMMessageUserTable> entrys = qb.list();
            if (entrys != null && entrys.size() > 0) {
                entry= entrys.get(0);
            }
        }catch (Exception e){

        }
        return entry;
    }

    /**
     * 获取最新的数据集合(倒序)
     * @param pageSize
     * @return
     */
    public List<IMMessageUserTable> getImUserEntryListDesc(int pageSize){
        if(pageSize<=0){
            pageSize = 5;
        }
        List<IMMessageUserTable > dataList = null ;
        try {
           QueryBuilder qb =imMessageTableDao.queryBuilder();
            qb.orderDesc(IMMessageUserTableDao.Properties.Listid);
            qb.limit(pageSize);
            dataList = qb.list();
        }catch (Exception e){

        }
        return dataList;
    }
    /**
     * 获取最新的数据集合(正序)
     * @param pageSize
     * @return
     */
    public List<IMMessageUserTable> getImUserEntryListAsc(int pageSize){
        if(pageSize<=0){
            pageSize = 5;
        }
        List<IMMessageUserTable > dataList = null ;
        try {
            QueryBuilder qb =imMessageTableDao.queryBuilder();
            qb.orderAsc(IMMessageUserTableDao.Properties.Listid);
            qb.limit(pageSize);
            dataList = qb.list();
        }catch (Exception e){

        }
        return dataList;
    }

    /**
     * 分页获取数据(倒序)
     * @param listId  开始listid（小于）
     * @param pageSize
     * @return
     */
    public List<IMMessageUserTable> getImUserEntryListByListIdDesc(Long listId, int pageSize){
        if(pageSize<=0){
            pageSize = 5;
        }
        List<IMMessageUserTable > dataList = new ArrayList<IMMessageUserTable>() ;
        try {
            QueryBuilder qb =imMessageTableDao.queryBuilder();
            qb.where(IMMessageUserTableDao.Properties.Listid.lt(listId));
            qb.orderDesc(IMMessageUserTableDao.Properties.Listid);
            qb.limit(pageSize);
            dataList = qb.list();
        }catch (Exception e){

        }
        return dataList;
    }
    /**
     * 分页获取数据(正序)
     * @param listId  开始listid（大于）
     * @param pageSize
     * @return  （null）
     */
    public List<IMMessageUserTable> getImUserEntryListByListIdAsc(Long listId, int pageSize){
        if(pageSize<=0){
            pageSize = 5;
        }
        List<IMMessageUserTable > dataList = null ;
        try {
            QueryBuilder qb =imMessageTableDao.queryBuilder();
            qb.where(IMMessageUserTableDao.Properties.Listid.gt(listId));
            qb.orderAsc(IMMessageUserTableDao.Properties.Listid);
            qb.limit(pageSize);
            dataList = qb.list();
        }catch (Exception e){

        }
        return dataList;
    }


    /**
     * 获取最新的数据集合(时间)(倒序)
     * @param pageSize
     * @return
     */
    public synchronized List<IMMessageUserTable> getImUserEntryListByCreateTimeDesc(int pageSize){
        if(pageSize<=0){
            pageSize = 5;
        }
        List<IMMessageUserTable > dataList = null ;
        try {
            QueryBuilder qb =imMessageTableDao.queryBuilder();
            qb.orderDesc(IMMessageUserTableDao.Properties.Create_time);
            qb.orderDesc(IMMessageUserTableDao.Properties.Listid);
            qb.limit(pageSize);
            dataList = qb.list();
        }catch (Exception e){

        }
        return dataList;
    }
    /**
     * 获取最新的数据集合(时间)(正序)
     * @param pageSize
     * @return
     */
    public synchronized List<IMMessageUserTable> getImUserEntryListByCreateTimeAsc(int pageSize){
        if(pageSize<=0){
            pageSize = 5;
        }
        List<IMMessageUserTable > dataList = null ;
        try {
            QueryBuilder qb =imMessageTableDao.queryBuilder();
            qb.orderAsc(IMMessageUserTableDao.Properties.Create_time);
            qb.orderAsc(IMMessageUserTableDao.Properties.Listid);
            qb.limit(pageSize);
            dataList = qb.list();
        }catch (Exception e){

        }
        return dataList;
    }
    /**
     * 分页获取数据（倒序）
     * @param  listId 开始listid（小于）
     * @param pageSize
     * @return
     */
    public synchronized List<IMMessageUserTable> getImUserEntryListByCreateTimeDesc(Long listId,String createTime, int pageSize){
        if(pageSize<=0){
            pageSize = 5;
        }
        List<IMMessageUserTable > dataList =null ;
        try {
            QueryBuilder qb =imMessageTableDao.queryBuilder();
            qb.where(IMMessageUserTableDao.Properties.Create_time.le(createTime));
            qb.where(IMMessageUserTableDao.Properties.Listid.lt(listId));
            qb.orderDesc(IMMessageUserTableDao.Properties.Create_time);
            qb.limit(pageSize);
            dataList = qb.list();
        }catch (Exception e){

        }
        return dataList;
    }
    /**
     * 分页获取数据(时间)（正序）
     * @param listId  开始listid（大于）
     * @param pageSize
     * @return
     */
    public synchronized List<IMMessageUserTable> getImUserEntryListByCreateTimeAsc(Long listId,String createTime, int pageSize){
        if(pageSize<=0){
            pageSize = 5;
        }
        List<IMMessageUserTable > dataList = null ;
        try {
            QueryBuilder qb =imMessageTableDao.queryBuilder();
            qb.where(IMMessageUserTableDao.Properties.Create_time.ge(createTime));
            qb.where(IMMessageUserTableDao.Properties.Listid.gt(listId));
            qb.orderAsc(IMMessageUserTableDao.Properties.Create_time);
            qb.limit(pageSize);
            dataList = qb.list();
        }catch (Exception e){

        }
        return dataList;
    }




    //==============================delete ========================

    /**
     * 删除指定的ImDefaultEntry
     * @param listId
     */
    public void delImUserEntryByMsgId(Long listId){
        imMessageTableDao.deleteByKey(listId);
    }


    /**
     * 删除全部数据
     */
    public void delImUserEntryAll(){
        imMessageTableDao.deleteAll();
    }

    //================================update==========================================
    /**
     * 更新某条数据
     * @param msgId
     */
    public synchronized void updateImDefaultEntryByMsgId(String msgId){
        IMMessageUserTable upEntry = getIMUserEntryByMsgId(msgId);
        if(upEntry!=null){
            upEntry.setIsRead(1);
            imMessageTableDao.update(upEntry);
        }
    }
    /**
     * 更新某条数据
     * @param listId
     */
    public synchronized void updateImDefaultEntryByListId(Long listId){
        IMMessageUserTable upEntry = getIMUserEntryByListId(listId);
        if(upEntry!=null){
            upEntry.setIsRead(1);
            imMessageTableDao.update(upEntry);
        }
    }
    /**
     * 更新全部的未读消息为已读
     */
    public synchronized void updateImDefaultEntryRead(){
        QueryBuilder qb =imMessageTableDao.queryBuilder();
        qb.where(IMMessageUserTableDao.Properties.IsRead.eq(0));
        List<IMMessageUserTable> entrys= qb.list();
        List<IMMessageUserTable> updateEntrys= new ArrayList<IMMessageUserTable>();
        for (IMMessageUserTable entry:entrys) {
            entry.setIsRead(1);
            updateEntrys.add(entry);
        }
        if(updateEntrys!=null && !updateEntrys.isEmpty()) {
            imMessageTableDao.updateInTx(updateEntrys);
        }

    }
}
